package net.jsoft.pms.web.mysql.versionplan;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;

import net.jsoft.platform.core.util.platform.PlatformUtils;
import net.jsoft.platform.core.web.BaseController;
import net.jsoft.pms.entity.plan.Plan;
import net.jsoft.pms.entity.versionplan.VersionPlan;
import net.jsoft.pms.repository.versionplan.VersionPlanRepository;
import net.sf.json.JSONObject;

/**
 * 版本计划
 *
 * @author John
 * @Date 2017-08-03 15:51:51
 */
@Controller
@RequestMapping("/vp")
public class VPController extends BaseController
{

    //    @Resource(name = "versionPlanServiceImpl")
    //    private IVersionPlanService service;

    private String PREFIX = "/pms/mysql/versionPlan/";

    @Autowired
    private VersionPlanRepository repository;

    @RequestMapping("/list")
    public String index()
    {
        return PREFIX + "list";
    }

    @RequestMapping("/listData")
    @ResponseBody
    public JSONObject listData(int pageSize, int pageNumber, final String beginDate, final String endDate) throws ParseException
    {
        Page<VersionPlan> list = null;
        List<VersionPlan> versionPlans = new ArrayList<VersionPlan>();
        Sort sort = new Sort(Sort.Direction.DESC, "publishDate");
        PageRequest request = new PageRequest(pageNumber - 1, pageSize, sort);

        list = repository.findAll(new Specification<VersionPlan>()
        {

            @Override
            public Predicate toPredicate(Root<VersionPlan> root, CriteriaQuery<?> query, CriteriaBuilder cb)
            {
                Predicate p = null;
                Predicate p1 = null;
                Predicate p2 = null;
                try
                {
                    if (StringUtils.isNotEmpty(beginDate) && StringUtils.isNotEmpty(endDate))
                    {
                        p1 = cb.between(root.get("publishDate").as(Date.class), PlatformUtils.getdate(beginDate), PlatformUtils.getdate(endDate));
                        p = cb.and(p1);
                    }
                    else
                    {
                        if (StringUtils.isNotEmpty(beginDate))
                        {
                            p1 = cb.greaterThanOrEqualTo(root.get("publishDate").as(Date.class), PlatformUtils.getdate(beginDate));
                            p = cb.and(p1);
                        }
                        if (StringUtils.isNotEmpty(endDate))
                        {
                            p2 = cb.lessThanOrEqualTo(root.get("publishDate").as(Date.class), PlatformUtils.getdate(endDate));
                            p = p1 == null ? p2 : cb.and(p1, p2);
                        }
                    }

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                return p;
            }
        }, request);
        versionPlans = new ArrayList<VersionPlan>();
        for (VersionPlan p : list.getContent())
        {
            versionPlans.add(p);
        }

        JSONObject json = new JSONObject();
        json.put("rows", versionPlans); //这里的 rows 和total 的key 是固定的 
        json.put("total", list.getTotalElements());
        return json;
    }

    @RequestMapping("/add")
    public String add()
    {
        return PREFIX + "add";
    }

    @RequestMapping("/addSave")
    @ResponseBody
    public String addSave(VersionPlan plan, String publishDateStr) throws ParseException
    {
        if (StringUtils.isNotEmpty(publishDateStr))
        {
            plan.setPublishDate(PlatformUtils.getdate(publishDateStr));
        }
        repository.save(plan);
        return "ok";
    }

    @RequestMapping("/edit")
    public String edit(long id, Model model)
    {
        VersionPlan plan = repository.findOne(id);
        model.addAttribute("plan", plan);
        return PREFIX + "edit";
    }

    @RequestMapping("/editSave")
    @ResponseBody
    public String editSave(VersionPlan plan, String publishDateStr) throws ParseException
    {
        //        plan = repository.findOne(plan.getId());
        if (StringUtils.isNotEmpty(publishDateStr))
        {
            plan.setPublishDate(PlatformUtils.getdate(publishDateStr));
        }
        repository.save(plan);
        return "ok";
    }

    public Map<String, Object> getNowVersions(String date)
    {
        Date d = null;
        try
        {
            if (StringUtils.isEmpty(date))
            {
                d = PlatformUtils.getdate((PlatformUtils.getdate(new Date())).substring(0, 10));
            }
            else
            {
                d = PlatformUtils.getdate(date);
            }
        }
        catch (ParseException e)
        {
            d = new Date();
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<String, Object>();
        final Map<String, Date> dates = PlatformUtils.getDays(d);
        List<VersionPlan> list = repository.findAll(new Specification<VersionPlan>()
        {
            @Override
            public Predicate toPredicate(Root<VersionPlan> root, CriteriaQuery<?> query, CriteriaBuilder cb)
            {
                Predicate p = null;
                Predicate p1 = null;
                try
                {
                    p1 = cb.between(root.get("publishDate").as(Date.class), dates.get("thisWeekMonday"), dates.get("thisWeekSunday"));
                    p = cb.and(p1);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                return p;
            }
        });
        VersionPlan nvp = new VersionPlan();

        if (list.size() == 1)
        {
            nvp = list.get(0);
        }
        else if (list.size() > 1)
        {

            Date now = new Date();
            VersionPlan temp = list.get(0);
            long l = Math.abs(now.getTime() - temp.getPublishDate().getTime());
            for (int i = 1; i < list.size(); i++)
            {
                if (Math.abs(list.get(i).getPublishDate().getTime() - now.getTime()) <= l)
                {
                    l = Math.abs(list.get(i).getPublishDate().getTime() - now.getTime());
                    temp = list.get(i);
                }
            }
            nvp = temp;
        }
        map.put("nowVersion", nvp);
        map.put("thisWeekVersion", list);

        return map;

    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/deskTop")
    @ResponseBody
    public Map<String, Object> deskTop(String date)
    {
        Map<String, Object> resp = new HashMap<String, Object>();

        Map<String, Object> nv = getNowVersions(date);
        Sort sort = new Sort(Direction.DESC, "id");
        List<VersionPlan> allVersionPlans = repository.findAll(new Specification<VersionPlan>()
        {
            @Override
            public Predicate toPredicate(Root<VersionPlan> root, CriteriaQuery<?> query, CriteriaBuilder cb)
            {
                Predicate p = null;
                return p;
            }
        }, sort);

        StringBuffer info = new StringBuffer();
        VersionPlan nvp = (VersionPlan) nv.get("nowVersion");
        info.append("版本计划：<br/> ");
        if (nvp == null || StringUtils.isEmpty(nvp.getVersion()))
        {
            info.append("本周暂无计划<br/>");
        }
        else
        {
            info.append("当前版本号为").append(nvp.getVersion()).append(" <br/>");
            info.append("本周版本号为： <br/>");
            List<VersionPlan> list = (List<VersionPlan>) nv.get("thisWeekVersion");
            for (VersionPlan v : list)
            {
                info.append("电子税务局版本号：").append(v.getVersion());
                info.append("，依赖核心征管版本号：").append(v.getDependOnVersion()).append("，");

                List<Plan> vpl = this.getVersionPlans(v.getVersion());
                List<Plan> vppl = this.getVersionPlansPublished(v.getVersion());
                info.append("计划出厂为：").append(vpl.size()).append("个,实际出厂为：").append(vppl.size());
                long vpp = 0;
                if (vpl.size() > 0)
                {
                    vpp = (vppl.size() / vpl.size()) * 100;
                }
                info.append("个，出厂率为").append(PlatformUtils.formattedDecimalToPercentage(vpp)).append("<br/> ");
            }

        }

        info.append("<div class=\"col-md-6\">");

        info.append("<select  id='versionPlanPage' class='js-example-data-array-selected'  style= 'width:50%'> ");

        for (VersionPlan v : allVersionPlans)
        {
            info.append("<option value = \"").append(v.getVersion()).append("\" ");

            if (v.getVersion().equals(nv.get("nowVersion")))
            {
                info.append(" selected = 'selected' ");
            }
            info.append(">");
            info.append(v.getVersion()).append("</option>");

        }

        info.append("</select> ");
        info.append("<button type='button' class='btn btn-primary'  id='versionPlanBtn'>查看</button> ");
        info.append("</div>");
        info.append("<br/> ");

        info.append("<script>");
        info.append("$(\".js-example-data-array-selected\").select2();");
        info.append("$(\"#versionPlanBtn\").click(function(){");
        info.append(" var version = $(\"#versionPlanPage\").val();");
        info.append(" openTab ('/vp/vpByVersion?version='+version,'版本计划');");
        info.append("});");
        info.append("</script>");

        resp.put("info", info.toString());
        return resp;
    }

    @RequestMapping("/getVersionPlans")
    @ResponseBody
    public List<Plan> getVersionPlans(String version)
    {

        List<Plan> planV = repository.findPlanByPlanVersion(version);
        return planV;

    }

    @RequestMapping("/getVersionPlansPublished")
    @ResponseBody
    public List<Plan> getVersionPlansPublished(String version)
    {

        List<Plan> planVP = repository.findPlanByPublishedVersion(version);
        return planVP;

    }

    @RequestMapping("/vpByVersion")
    public String vpByVersion(String version, Model model)
    {
        StringBuffer info = new StringBuffer();
        VersionPlan vp = repository.findOneByVersion(version);
        info.append("电子税务局版本号：").append(vp.getVersion());
        info.append("，依赖核心征管版本号：").append(vp.getDependOnVersion()).append("，");
        info.append("，发布日期：").append(vp.getDependOnVersion()).append("，");
        List<Plan> vpl = this.getVersionPlans(vp.getVersion());
        List<Plan> vppl = this.getVersionPlansPublished(vp.getVersion());

        model.addAttribute("vpl", vpl);
        model.addAttribute("vppl", vppl);

        return PREFIX + "vpByVersion";

    }

    public VersionPlan getVersionPlan(String version)
    {
        return repository.findOneByVersion(version);
    }

    @RequestMapping("/getAllVP")
    public String getAllVP(Model model)
    {
        Sort sort = new Sort(Sort.Direction.DESC, "publishDate");
        Iterable<VersionPlan> it = repository.findAll(sort);
        List<VersionPlan> myList = Lists.newArrayList(it);
        model.addAttribute("vps", myList);
        return PREFIX + "getAllVP";
    }

    @RequestMapping("/getAllVPData")
    @ResponseBody
    public List<VersionPlan> getAllVPData()
    {
        Sort sort = new Sort(Sort.Direction.DESC, "publishDate");
        Iterable<VersionPlan> it = repository.findAll(sort);
        List<VersionPlan> myList = Lists.newArrayList(it);
        return myList;
    }

}
